<template>
  <div class="snapshot-analysis-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">路由快照分析</h1>
      <p class="page-subtitle">实时监控和分析RIP协议路由表变化历史</p>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <template #header>
          <div class="filter-header">
            <span class="filter-title">数据筛选</span>
            <el-button type="primary" text @click="loadAllData">刷新数据</el-button>
          </div>
        </template>
        
        <el-form :model="filterForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="拓扑结构">
                <el-select 
                  v-model="filterForm.topologyId" 
                  placeholder="选择拓扑" 
                  clearable
                  filterable
                  @change="handleTopologyChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="topology in topologyList"
                    :key="topology.id"
                    :label="topology.name"
                    :value="topology.id"
                  >
                    <div class="topology-option">
                      <span class="topology-name">{{ topology.name }}</span>
                      <span class="topology-desc">{{ topology.description }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="仿真实例">
                <el-select 
                  v-model="filterForm.simulationId" 
                  placeholder="选择仿真" 
                  clearable
                  filterable
                  @change="handleSimulationChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="simulation in simulationList"
                    :key="simulation.id"
                    :label="`仿真-${simulation.id}`"
                    :value="simulation.id"
                  >
                    <div class="simulation-option">
                      <span class="simulation-id">仿真 {{ simulation.id }}</span>
                      <span class="simulation-time">{{ formatTime(simulation.createdAt) }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="路由器">
                <el-select 
                  v-model="filterForm.routerId" 
                  placeholder="选择路由器" 
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="router in routerList"
                    :key="router.routerId"
                    :label="`路由器 ${router.routerId}`"
                    :value="router.routerId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="24">
              <div class="filter-actions">
                <el-button 
                  type="primary" 
                  @click="loadSnapshots" 
                  :loading="loading"
                  :disabled="!canLoadSnapshots"
                >
                  <el-icon><Search /></el-icon>
                  查询快照
                </el-button>
                <el-button @click="resetFilter">
                  <el-icon><Refresh /></el-icon>
                  重置条件
                </el-button>
                <el-button 
                  type="success" 
                  @click="loadLatestSnapshot" 
                  :disabled="!canLoadLatest"
                >
                  <el-icon><Clock /></el-icon>
                  获取最新状态
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- 数据展示区域 - 使用方案3布局 -->
    <div class="content-section-responsive">
      <!-- 快照时间线 -->
      <el-card class="timeline-card-responsive">
        <template #header>
          <div class="card-header">
            <span class="card-title">路由快照历史时间线</span>
            <div class="card-actions">
              <span class="snapshot-count">共 {{ snapshots.length }} 个快照</span>
              <el-button 
                size="small" 
                type="danger" 
                @click="clearSnapshots" 
                :disabled="!canClearSnapshots"
              >
                <el-icon><Delete /></el-icon>
                清空快照
              </el-button>
            </div>
          </div>
        </template>

        <div v-if="snapshots.length === 0" class="empty-state">
          <el-empty description="暂无快照数据" />
        </div>

        <el-timeline v-else>
          <el-timeline-item
            v-for="snapshot in snapshots"
            :key="snapshot.id"
            :timestamp="formatDetailedTime(snapshot.timestamp)"
            placement="top"
            :type="getSnapshotType(snapshot)"
          >
            <el-card class="snapshot-card" :class="{ 'latest-snapshot': isLatestSnapshot(snapshot) }">
              <template #header>
                <div class="snapshot-header">
                  <div class="snapshot-info">
                    <span class="router-id">路由器 {{ snapshot.routerId }}</span>
                    <el-tag :type="getTagType(snapshot)" size="small">
                      {{ snapshot.routeCount || 0 }} 条路由
                    </el-tag>
                    <el-tag v-if="isLatestSnapshot(snapshot)" type="success" size="small">
                      最新状态
                    </el-tag>
                  </div>
                  <el-button 
                    size="small" 
                    @click="viewSnapshotDetail(snapshot)"
                  >
                    查看详情
                  </el-button>
                </div>
              </template>

              <div class="route-preview">
                <div 
                  v-for="(route, index) in getPreviewRoutes(snapshot)" 
                  :key="index"
                  class="route-item"
                >
                  <span class="destination">{{ route.destination }}</span>
                  <span class="next-hop">→ {{ route.nextHop }}</span>
                  <span class="metric">(度量: {{ route.metric }})</span>
                </div>
                <div v-if="hasMoreRoutes(snapshot)" class="more-routes">
                  还有 {{ getRemainingRouteCount(snapshot) }} 条路由...
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>

      <!-- 最新快照详情 -->
      <el-card class="detail-card-responsive" v-if="latestSnapshot">
        <template #header>
          <div class="card-header">
            <span class="card-title">最新路由表详情</span>
            <el-tag type="success">实时状态</el-tag>
          </div>
        </template>

        <div class="latest-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="路由器ID">{{ latestSnapshot.routerId }}</el-descriptions-item>
            <el-descriptions-item label="快照时间">{{ formatDetailedTime(latestSnapshot.timestamp) }}</el-descriptions-item>
            <el-descriptions-item label="路由数量">{{ latestSnapshot.routeCount || 0 }}</el-descriptions-item>
            <el-descriptions-item label="拓扑ID">{{ filterForm.topologyId }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <el-table 
          :data="latestSnapshot.routes" 
          size="small" 
          stripe
          class="route-table"
        >
          <el-table-column prop="destination" label="目标网络" min-width="120">
            <template #default="{ row }">
              <span class="destination-cell">{{ row.destination }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="nextHop" label="下一跳地址" min-width="120">
            <template #default="{ row }">
              <span class="next-hop-cell">{{ row.nextHop }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="metric" label="度量值" width="100">
            <template #default="{ row }">
              <el-tag :type="getMetricTagType(row.metric)" size="small">
                {{ row.metric }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag v-if="row.metric < 16" type="success" size="small">可达</el-tag>
              <el-tag v-else type="danger" size="small">不可达</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      
      <!-- 占位卡片 -->
      <div class="placeholder-card" v-else>
        <div class="placeholder-content">
          <el-icon size="48" color="#c0c4cc"><InfoFilled /></el-icon>
          <p>暂无最新路由状态数据</p>
          <p class="placeholder-tip">选择拓扑和路由器后点击"获取最新状态"</p>
        </div>
      </div>
    </div>

    <!-- 快照详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      :title="`路由器 ${selectedSnapshot?.routerId} 的路由表`"
      width="800px"
    >
      <div v-if="selectedSnapshot" class="snapshot-detail">
        <div class="detail-meta">
          <span>快照时间: {{ formatDetailedTime(selectedSnapshot.timestamp) }}</span>
          <span>路由数量: {{ selectedSnapshot.routeCount || 0 }}</span>
        </div>
        
        <el-table :data="selectedSnapshot.routes" size="small" stripe>
          <el-table-column prop="destination" label="目标网络" width="200" />
          <el-table-column prop="nextHop" label="下一跳" width="150" />
          <el-table-column prop="metric" label="度量值" width="100">
            <template #default="{ row }">
              <el-tag :type="getMetricTagType(row.metric)" size="small">
                {{ row.metric }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag v-if="row.metric < 16" type="success" size="small">可达</el-tag>
              <el-tag v-else type="danger" size="small">不可达</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Clock,
  Delete,
  InfoFilled
} from '@element-plus/icons-vue'

// 按照您的项目风格导入 http
import http from '../api/http'

// 响应式数据
const loading = ref(false)
const topologyList = ref([])
const simulationList = ref([])
const routerList = ref([])
const snapshots = ref([])
const latestSnapshot = ref(null)
const selectedSnapshot = ref(null)
const detailDialogVisible = ref(false)
const autoSelectedRouter = ref(null)

// 筛选表单
const filterForm = reactive({
  topologyId: null,
  simulationId: null,
  routerId: null
})

// 计算属性
const canLoadLatest = computed(() => {
  return filterForm.topologyId && filterForm.routerId
})

const canClearSnapshots = computed(() => {
  return filterForm.topologyId || filterForm.simulationId
})

const canLoadSnapshots = computed(() => {
  return filterForm.topologyId || filterForm.simulationId
})

// 生命周期
onMounted(() => {
  loadTopologies()
  checkAutoSelection()
})

// 模拟数据函数 - 用于后端接口不可用时
function getMockSnapshots() {
  return [
    {
      id: 1,
      routerId: 'R1',
      timestamp: new Date().toISOString(),
      routeCount: 3,
      routes: [
        { destination: '192.168.1.0/24', nextHop: 'Direct', metric: 1 },
        { destination: '192.168.2.0/24', nextHop: 'R2', metric: 2 },
        { destination: '192.168.3.0/24', nextHop: 'R3', metric: 3 }
      ]
    },
    {
      id: 2,
      routerId: 'R2', 
      timestamp: new Date(Date.now() - 300000).toISOString(),
      routeCount: 2,
      routes: [
        { destination: '192.168.1.0/24', nextHop: 'R1', metric: 2 },
        { destination: '192.168.2.0/24', nextHop: 'Direct', metric: 1 }
      ]
    },
    {
      id: 3,
      routerId: 'R3',
      timestamp: new Date(Date.now() - 600000).toISOString(),
      routeCount: 2,
      routes: [
        { destination: '192.168.1.0/24', nextHop: 'R1', metric: 3 },
        { destination: '192.168.3.0/24', nextHop: 'Direct', metric: 1 }
      ]
    }
  ]
}

// 数据加载方法
async function loadTopologies() {
  try {
    const resp = await http.get('/api/topologies')
    // 预期 resp.data 是数组
    topologyList.value = Array.isArray(resp?.data) ? resp.data : (resp?.data?.items ?? [])
  } catch (error) {
    console.error('加载拓扑列表失败:', error)
    ElMessage.error('加载拓扑列表失败')
  }
}

function checkAutoSelection() {
  try {
    const storedRouter = localStorage.getItem('selectedRouterForSnapshot');
    if (storedRouter) {
      const routerInfo = JSON.parse(storedRouter);
      autoSelectedRouter.value = routerInfo;
      
      // 自动设置拓扑ID
      if (routerInfo.topologyId) {
        filterForm.topologyId = routerInfo.topologyId;
        
        // 延迟加载拓扑详情，确保拓扑选择生效
        setTimeout(() => {
          handleTopologyChange(routerInfo.topologyId).then(() => {
            // 拓扑加载完成后自动设置路由器
            if (routerInfo.routerId) {
              // 等待路由器列表加载完成
              setTimeout(() => {
                filterForm.routerId = routerInfo.routerId;
                // 自动加载快照数据
                loadSnapshots();
                ElMessage.success(`已自动选中路由器 ${routerInfo.label || routerInfo.routerId}`);
              }, 500);
            }
          });
        }, 100);
      }
      
      // 清理存储的数据，避免重复自动选择
      localStorage.removeItem('selectedRouterForSnapshot');
    }
  } catch (error) {
    console.error('自动选中路由器失败:', error);
  }
}

async function handleTopologyChange(topologyId) {
  if (!topologyId) {
    simulationList.value = []
    routerList.value = []
    return
  }

  try {
    // 加载该拓扑的仿真列表
    try {
      const simResp = await http.get(`/api/simulations/topology/${topologyId}`)
      simulationList.value = Array.isArray(simResp?.data) ? simResp.data : (simResp?.data?.items ?? [])
    } catch (simError) {
      console.warn('加载仿真列表失败，使用空数组:', simError)
      simulationList.value = []
    }

    // 加载该拓扑的路由器列表
    try {
      const topoResp = await http.get(`/api/topologies/${topologyId}`)
      const topology = topoResp?.data || {}
      routerList.value = Array.isArray(topology.routers) ? topology.routers : []
      
      // 如果有自动选中的路由器，确保它在列表中
      if (autoSelectedRouter.value && autoSelectedRouter.value.routerId) {
        const routerExists = routerList.value.some(
          router => String(router.routerId) === String(autoSelectedRouter.value.routerId)
        );
        if (!routerExists) {
          console.warn('自动选中的路由器不在当前拓扑中:', autoSelectedRouter.value.routerId);
          autoSelectedRouter.value = null;
        }
      }
    } catch (topoError) {
      console.warn('加载路由器列表失败，使用空数组:', topoError)
      routerList.value = []
    }
  } catch (error) {
    console.error('加载拓扑详情失败:', error)
  }
}
async function handleSimulationChange(simulationId) {
  if (!simulationId) return
  console.log('选择仿真:', simulationId)
}

async function loadSnapshots() {
  // 参数验证
  const { topologyId, simulationId, routerId } = filterForm
  if (!topologyId && !simulationId) {
    ElMessage.warning('请至少选择拓扑或仿真')
    return
  }
  if (routerId && !topologyId) {
    ElMessage.warning('选择路由器时必须先选择拓扑')
    return
  }

  loading.value = true
  try {
    let resp
    
    try {
      // 使用新的组合查询接口
      const params = {}
      if (topologyId) params.topologyId = topologyId
      if (simulationId) params.simulationId = simulationId
      if (routerId) params.routerId = routerId
      
      console.log('查询参数:', params) // 调试用
      resp = await http.get('/api/snapshots/filter', { params })
      
    } catch (apiError) {
      console.warn('组合查询接口失败，回退到原有接口:', apiError)
      // 回退逻辑
      if (simulationId) {
        resp = await http.get(`/api/snapshots/simulation/${simulationId}`)
      } else if (topologyId && routerId) {
        resp = await http.get(`/api/snapshots/topology/${topologyId}/router/${routerId}`)
      } else if (topologyId) {
        resp = await http.get(`/api/snapshots/topology/${topologyId}`)
      }
    }
    
    // 数据处理逻辑
    const rawData = Array.isArray(resp?.data) ? resp.data : (resp?.data?.items ?? [])
    console.log('原始响应数据:', rawData) // 调试用
    
    snapshots.value = rawData.map(item => {
      let routes = []
      let routeCount = 0
      
      try {
        // 优先使用后端解析好的routes
        if (item.routes && Array.isArray(item.routes)) {
          routes = item.routes
          routeCount = routes.length
        } 
        // 如果后端没有解析，前端自己解析routeJson
        else if (item.routeJson) {
          const routeData = JSON.parse(item.routeJson)
          
          // 处理新旧两种JSON格式
          if (routeData.entries && Array.isArray(routeData.entries)) {
            // 新格式：包含entries字段
            routes = routeData.entries
            routeCount = routes.length
            console.log('使用新格式解析路由，数量:', routeCount)
          } else if (Array.isArray(routeData)) {
            // 旧格式：直接是路由数组
            routes = routeData
            routeCount = routes.length
            console.log('使用旧格式解析路由，数量:', routeCount)
          } else {
            console.warn('未知的路由数据格式:', routeData)
            routes = []
            routeCount = 0
          }
        }
      } catch (e) {
        console.error('解析路由数据失败:', e, '原始数据:', item.routeJson)
        routes = []
        routeCount = 0
      }
      
      // 处理时间戳字段，兼容多种可能的字段名
      const timestamp = item.timestamp || item.snapshotTime || item.snapshot_time
      
      return {
        id: item.id,
        routerId: item.routerId || item.router_id,
        timestamp: timestamp,
        formattedTime: item.formattedTime, // 使用后端格式化好的时间
        routeCount: routeCount,
        routes: routes,
        simulationId: item.simulationId || item.simulation_id,
        routeJson: item.routeJson // 保留原始JSON用于调试
      }
    })
    
    latestSnapshot.value = null
    
    // 按时间排序（确保最新的在前面）
    snapshots.value.sort((a, b) => {
      const timeA = new Date(a.timestamp).getTime()
      const timeB = new Date(b.timestamp).getTime()
      return timeB - timeA
    })

    if (snapshots.value.length > 0) {
      // 自动设置第一个（最新的）快照为最新快照
      const latest = snapshots.value[0]
      latestSnapshot.value = {
        ...latest,
        // 确保有所有必要的字段
        formattedTime: latest.formattedTime || formatDetailedTime(latest.timestamp)
      }
      ElMessage.success(`加载到 ${snapshots.value.length} 个快照`)
    } else {
      ElMessage.info('未找到符合条件的快照数据')
    }
    
    if (snapshots.value.length > 0) {
      ElMessage.success(`加载到 ${snapshots.value.length} 个快照`)
      console.log('处理后的快照数据:', snapshots.value)
    } else {
      ElMessage.info('未找到符合条件的快照数据')
    }
  } catch (error) {
    console.error('加载快照失败:', error)
    ElMessage.error('加载快照数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}
async function loadLatestSnapshot() {
  if (!canLoadLatest.value) {
    ElMessage.warning('请先选择拓扑和路由器')
    return
  }

  try {
    const resp = await http.get(
      `/api/snapshots/topology/${filterForm.topologyId}/router/${filterForm.routerId}/latest`
    )
    
    if (resp.data) {
      const latestData = resp.data
      let routes = []
      let routeCount = 0
      
      try {
        // 修复：使用与 loadSnapshots 相同的解析逻辑
        if (latestData.routes && Array.isArray(latestData.routes)) {
          routes = latestData.routes
          routeCount = routes.length
        } else if (latestData.routeJson) {
          const routeData = JSON.parse(latestData.routeJson)
          
          // 处理新旧两种JSON格式
          if (routeData.entries && Array.isArray(routeData.entries)) {
            // 新格式：包含entries字段
            routes = routeData.entries
            routeCount = routes.length
          } else if (Array.isArray(routeData)) {
            // 旧格式：直接是路由数组
            routes = routeData
            routeCount = routes.length
          } else {
            console.warn('未知的路由数据格式:', routeData)
            routes = []
            routeCount = 0
          }
        }
      } catch (e) {
        console.error('解析最新快照路由数据失败:', e, '原始数据:', latestData.routeJson)
        routes = []
        routeCount = 0
      }
      
      latestSnapshot.value = {
        id: latestData.id,
        routerId: latestData.routerId || latestData.router_id,
        simulationId: latestData.simulationId || latestData.simulation_id,
        timestamp: latestData.timestamp || latestData.formattedTime || latestData.snapshotTime,
        routeCount: routeCount,
        routes: routes,
        formattedTime: latestData.formattedTime // 添加格式化时间
      }
      
      ElMessage.success('已获取最新路由状态')
    } else {
      ElMessage.info('该路由器暂无快照数据')
    }
  } catch (error) {
    console.error('获取最新快照失败:', error)
    // 提供更详细的错误信息
    if (error.response?.status === 404) {
      ElMessage.warning('未找到该路由器的最新快照数据')
    } else {
      ElMessage.error('获取最新路由状态失败: ' + (error.message || '未知错误'))
    }
  }
}
async function clearSnapshots() {
  if (!canClearSnapshots.value) {
    ElMessage.warning('请选择要清空的拓扑或仿真')
    return
  }

  try {
    await ElMessageBox.confirm(
      '此操作将永久删除所有相关快照数据，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const { topologyId, simulationId } = filterForm
    
    if (simulationId) {
      await http.delete(`/api/snapshots/simulation/${simulationId}`)
      ElMessage.success('已清空该仿真的所有快照')
    } else if (topologyId) {
      await http.delete(`/api/snapshots/topology/${topologyId}`)
      ElMessage.success('已清空该拓扑的所有快照')
    }
    
    // 重新加载数据
    loadSnapshots()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空快照失败:', error)
      ElMessage.error('清空快照失败')
    }
  }
}

// 工具方法
function resetFilter() {
  filterForm.topologyId = null
  filterForm.simulationId = null
  filterForm.routerId = null
  simulationList.value = []
  routerList.value = []
  snapshots.value = []
  latestSnapshot.value = null
}

function loadAllData() {
  loadTopologies()
  if (filterForm.topologyId || filterForm.simulationId) {
    loadSnapshots()
  }
}

function formatTime(timestamp) {
  if (!timestamp) return '未知时间'
  return new Date(timestamp).toLocaleString('zh-CN')
}

function formatDetailedTime(timestamp) {
  if (!timestamp) return '未知时间'
  
  try {
    // 处理可能的 ISO 格式和字符串格式
    const date = new Date(timestamp)
    if (isNaN(date.getTime())) {
      return '无效时间'
    }
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    console.error('时间格式化错误:', e)
    return '时间格式错误'
  }
}

function getSnapshotType(snapshot) {
  // 可以根据快照特征返回不同的类型
  return 'primary'
}

function getTagType(snapshot) {
  const routeCount = snapshot.routeCount || 0
  if (routeCount === 0) return 'danger'
  if (routeCount < 5) return 'warning'
  return 'success'
}

function getMetricTagType(metric) {
  if (metric === 1) return 'success'
  if (metric < 5) return 'warning'
  if (metric < 16) return 'danger'
  return 'info'
}

function isLatestSnapshot(snapshot) {
  if (!latestSnapshot.value) return false
  return snapshot.id === latestSnapshot.value.id
}

function getPreviewRoutes(snapshot) {
  const routes = snapshot.routes || []
  return routes.slice(0, 3) // 预览前3条路由
}

function hasMoreRoutes(snapshot) {
  const routes = snapshot.routes || []
  return routes.length > 3
}

function getRemainingRouteCount(snapshot) {
  const routes = snapshot.routes || []
  return routes.length - 3
}

function viewSnapshotDetail(snapshot) {
  selectedSnapshot.value = snapshot
  detailDialogVisible.value = true
}
</script>

<style scoped>
.snapshot-analysis-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 8px 0 0 0;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-title {
  font-size: 16px;
  font-weight: 600;
}

.topology-option {
  display: flex;
  flex-direction: column;
}

.topology-name {
  font-weight: 500;
}

.topology-desc {
  font-size: 12px;
  color: #909399;
}

.simulation-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.simulation-time {
  font-size: 12px;
  color: #909399;
}

.filter-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 16px;
}

/* 方案3：智能响应式布局 */
.content-section-responsive {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 20px;
  align-items: stretch; /* 等高对齐 */
}

.timeline-card-responsive,
.detail-card-responsive,
.placeholder-card {
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.timeline-card-responsive {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.detail-card-responsive,
.placeholder-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
}

.placeholder-card {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.placeholder-content {
  text-align: center;
  color: #909399;
}

.placeholder-content p {
  margin: 12px 0 0 0;
  font-size: 14px;
}

.placeholder-tip {
  font-size: 12px !important;
  color: #c0c4cc;
}

/* 卡片内部布局 */
.timeline-card-responsive :deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.timeline-card-responsive :deep(.el-card__body) {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.detail-card-responsive :deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-card-responsive :deep(.el-card__body) {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 原有样式保持不变 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.snapshot-count {
  font-size: 14px;
  color: #909399;
  margin-right: 12px;
}

.empty-state {
  padding: 40px 0;
}

.snapshot-card {
  margin-bottom: 8px;
  transition: all 0.3s ease;
}

.snapshot-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.snapshot-card.latest-snapshot {
  border-left: 4px solid #67c23a;
}

.snapshot-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.snapshot-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.router-id {
  font-weight: 500;
  color: #303133;
}

.route-preview {
  max-height: 120px;
  overflow-y: auto;
}

.route-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  margin: 2px 0;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 12px;
}

.destination {
  font-weight: 500;
  color: #303133;
}

.next-hop {
  color: #606266;
}

.metric {
  color: #e6a23c;
  font-weight: 500;
}

.more-routes {
  text-align: center;
  color: #909399;
  font-size: 12px;
  padding: 8px;
  font-style: italic;
}

.latest-info {
  margin-bottom: 16px;
}

.route-table {
  flex: 1;
  overflow-y: auto;
}

.destination-cell {
  font-family: 'Courier New', monospace;
  font-weight: 500;
}

.next-hop-cell {
  font-family: 'Courier New', monospace;
}

.snapshot-detail .detail-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-section-responsive {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .timeline-card-responsive,
  .detail-card-responsive,
  .placeholder-card {
    min-height: 400px;
  }
}

@media (max-width: 768px) {
  .snapshot-analysis-container {
    padding: 12px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .filter-actions {
    flex-direction: column;
  }
  
  .snapshot-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .content-section-responsive {
    gap: 12px;
  }
  
  .timeline-card-responsive,
  .detail-card-responsive,
  .placeholder-card {
    min-height: 300px;
  }
}
</style>